package com.lucksoft.map.sdk.baidu.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lucksoft.core.response.ApiResult;
import com.lucksoft.core.constant.BaseOperateConstant;

/**
 * 百度地图路线规划服务类
 * 
 * @author Qwen
 * @date 2025/10/9
 * @version 1.0.0
 */
@Service
public class MapSdkBaiduService {
    
    private static final Logger logger = LoggerFactory.getLogger(MapSdkBaiduService.class);
    
    private static final String BASE_URL = "https://api.map.baidu.com";
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 获取路线规划信息
     * 
     * @param origin 起点坐标(纬度,经度)
     * @param destination 终点坐标(纬度,经度)
     * @param routeType 路线类型(driving, walking, riding)
     * @param tactics 路线偏好
     * @param ak 百度地图API Key
     * @return ApiResult 路线信息
     */
    public ApiResult getRouteInfo(String origin, String destination, String routeType, String tactics, String ak) {
        try {
            String apiUrl;
            Map<String, String> params = new HashMap<>();
            
            // 根据路线类型选择API接口
            switch (routeType) {
                case "driving":
                    apiUrl = BASE_URL + "/direction/v2/driving";
                    params.put("origin", origin);
                    params.put("destination", destination);
                    params.put("ak", ak);
                    params.put("tactics", tactics);
                    params.put("ret_fields", "toll,toll_distance,traffic_light");
                    break;
                case "walking":
                    apiUrl = BASE_URL + "/direction/v2/walking";
                    params.put("origin", origin);
                    params.put("destination", destination);
                    params.put("ak", ak);
                    break;
                case "riding":
                    apiUrl = BASE_URL + "/direction/v2/riding";
                    params.put("origin", origin);
                    params.put("destination", destination);
                    params.put("ak", ak);
                    break;
                default:
                    logger.warn("不支持的路线类型: {}", routeType);
                    return new ApiResult(BaseOperateConstant.FAILURE_CODE, "不支持的路线类型", null);
            }
            
            logger.info("请求百度地图API: {}, 参数: {}", apiUrl, params);
            
            // 构建请求URL
            UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(apiUrl);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.queryParam(entry.getKey(), entry.getValue());
            }
            String requestUrl = builder.toUriString();
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                requestUrl, 
                HttpMethod.GET, 
                entity, 
                String.class
            );
            
            if (response.getStatusCode().is2xxSuccessful()) {
                Map<String, Object> result = objectMapper.readValue(response.getBody(), new TypeReference<Map<String, Object>>() {});
                
                logger.info("百度地图API响应状态: {}", result.get("status"));
                
                // 检查百度地图API返回状态
                Integer status = (Integer) result.get("status");
                if (status != null && status == 0) {
                    return new ApiResult(BaseOperateConstant.SUCCESS_CODE, "请求成功", result);
                } else {
                    String errorMsg = "百度地图API错误: " + result.get("message");
                    logger.error(errorMsg);
                    return new ApiResult(BaseOperateConstant.FAILURE_CODE, errorMsg, null);
                }
            } else {
                String errorMsg = "请求失败，状态码: " + response.getStatusCode();
                logger.error(errorMsg);
                return new ApiResult(BaseOperateConstant.FAILURE_CODE, errorMsg, null);
            }
            
        } catch (Exception e) {
            String errorMsg = "请求百度地图API异常: " + e.getMessage();
            logger.error(errorMsg, e);
            return new ApiResult(BaseOperateConstant.FAILURE_CODE, errorMsg, null);
        }
    }
}